package org.mtmi.io.controls;

import java.io.IOException;

import net.n3.nanoxml.IXMLElement;

import org.mtmi.io.ReaderError;
import org.mtmi.io.SceneReader;
import org.mtmi.io.SceneWriter;
import org.mtmi.io.XMLReader;
import org.mtmi.io.XMLWriter;
import org.mtmi.ui.controls.Control;
import org.mtmi.ui.controls.IValueGenerator;
import org.mtmi.ui.controls.Keyboard;

/**
 * In addition to {@link ControlIO}, save {@link Keyboard} features:
 * <ul>
 * <li> keyboard leftward key value 
 * <li> keyboard transpose value
 * <li> keyboard octave count
 * <li> keyboard transpose controller if any
 * </ul>
 */
public class KeyboardIO extends ControlIO
{
	
	private static final String E_KEYBOARD = "keyboard"; //$NON-NLS-1$
	private static final String A_KEY0 = "leftKeyValue"; //$NON-NLS-1$
	private static final String A_TR = "transpose"; //$NON-NLS-1$
	private static final String A_OC = "octaveCount"; //$NON-NLS-1$
	private static final String A_TC = "transposeController"; //$NON-NLS-1$
	private static final String A_TCCID = "transposeControllerCID"; //$NON-NLS-1$

	public KeyboardIO() {
		//Not:yet: setProcessFeature( F_BACKGROUND_COLOR, true );
		//Not:yet: setProcessFeature( F_FOREGROUND_COLOR, true );
	}
	
	@Override
	public void writeControl( Control c, XMLWriter w, SceneWriter sw ) throws IOException 
	{
		super.writeControl(c, w, sw);
		
		//keyboard:
		Keyboard kb = (Keyboard)c;
		boolean ai = w.setAttributeIndented( false );
		w.startElement( E_KEYBOARD );
		w.addAttr( A_KEY0, kb.getValue0() );
		w.addAttr( A_TR, kb.getTranspose() );
		w.addAttr( A_OC, kb.getOctaveCount() );
		if( kb.getTransposeController()!=null ) {
			w.addAttr( A_TC, sw.getControlId( (Control)kb.getTransposeController() ) );
			w.addAttr( A_TCCID, kb.getTransposeControllerConnectionId(), (String)null );
		}
		w.setAttributeIndented( ai );
		w.endElement( E_KEYBOARD );
	}
	
	@Override
	public void readControl( Control c, IXMLElement element, XMLReader r, SceneReader sr ) throws ReaderError 
	{
		super.readControl(c, element, r, sr);
		
		Keyboard kb = (Keyboard)c;
		
		//keyboard:		
		IXMLElement e = r.getElement( element, E_KEYBOARD, true );
		
		kb.setValue0( r.getAttrInt( e, A_KEY0 ) );
		kb.setTranspose( r.getAttrInt( e, A_TR ) );
		kb.setOctaveCount( r.getAttrInt( e, A_OC ) );
		
		int id = r.getAttr( e, A_TC, 0 ) ;
		String cid = r.getAttr( e, A_TCCID, (String)null );
		if( id>0 ) {
			Control tc = sr.getControl( id );
			if( tc instanceof IValueGenerator ) {
				kb.setTransposeController( (IValueGenerator)tc, cid );
			}
		}
	}
}
